package dao

import (
	"context"
	"gorm.io/gorm"
	"todo-list/repository/db/model"
)

type UserDao struct {
	DB *gorm.DB
}

func (dao *UserDao) FindUserByUserName(userName string) (user *model.User, err error) {
	err = dao.DB.Model(user).Where("user_name = ?", userName).Take(&user).Error
	return
}

func (dao *UserDao) FindUserByUserId(userId uint) (user *model.User, err error) {
	err = dao.DB.Model(user).Take(&user, userId).Error
	return
}

func (dao *UserDao) FindUserByEmail(email string) (user *model.User, err error) {
	err = dao.DB.Model(user).Where("email = ?", email).Take(&user).Error
	return
}

func (dao *UserDao) FindUserByUserNameOrEmail(loginKey string) (user *model.User, err error) {
	err = dao.DB.Model(user).Where("user_name = ?", loginKey).Or("email = ?", loginKey).Take(&user).Error
	return
}

func (dao *UserDao) CheckExist(userId uint, userName, email string) (exist bool, err error) {
	result := dao.DB.Model(model.User{}).Where("id = ?", userId).Or("user_name = ?", userName).Or("email = ?", email).Find(&[]model.User{})
	count := result.RowsAffected
	err = result.Error
	return count > 0, err
}

func (dao *UserDao) CreateUser(user *model.User) (err error) {
	err = dao.DB.Model(user).Create(user).Error
	return
}

func (dao *UserDao) UpdateUser(user *model.User) (err error) {
	return dao.DB.Model(user).Save(user).Error
}

func NewUserDao(ctx context.Context) *UserDao {
	if ctx == nil {
		ctx = context.Background()
	}
	return &UserDao{NewDBClient(ctx)}
}
